package com.ruoyi.modules.util.wechar;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jdom2.JDOMException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;


@Slf4j
public class WeCharPayRequestUtil {

    //加密 解密默认编码
    private final static String characterEncoding = "UTF-8";
    //微信接口地址
    private final static String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";//请求下单的http



    public final static String MCH_ID = "1619461147";//商户号
    public final static String APP_ID = "wx39898f7474d916d0";//微信开放平台 服务号的应用号
    public final static String WX_PAY_API_KEY = "3750yerhwioydsaf0psrfqr231413423";//API密钥
    //回调地址
    public final static String notify_url = "https://duoduodan1688.cn/dy/app/payPayInfo/openApi/wx/callback";



    public static void main(String[] args){

        try {
            Map<String, String> map = wxUnifiedPay("123456123456", new BigDecimal(1), "支付测试");
            System.out.println(map);
        } catch (Exception e) {
            log.info("下单失败！");
            e.printStackTrace();
        }
    }


    /*
     * 通用下单数据封装
     * */
    public static Map<String, String> wxUnifiedPay(String outTradeNo, BigDecimal payPrice, String message) throws JDOMException, IOException {


        //微信要求  12.34元 要转成为 1234
        int CentsPayPrice = payPrice.multiply(new BigDecimal(100)).intValue();
        SortedMap<Object, Object> requestParameters = new TreeMap<Object, Object>();
        requestParameters.put("appid", APP_ID);
        requestParameters.put("mch_id", MCH_ID);
        requestParameters.put("nonce_str", WxUtil.CreateNoncestr());
        requestParameters.put("body", message);
        requestParameters.put("out_trade_no", outTradeNo); //订单id
        requestParameters.put("fee_type", "CNY");
        requestParameters.put("total_fee", String.valueOf(CentsPayPrice));
        requestParameters.put("spbill_create_ip", WxUtil.getHostIp());
        requestParameters.put("notify_url", notify_url);
        requestParameters.put("trade_type", "NATIVE");
        //设置签名
        String sign = createSignFun(characterEncoding,requestParameters, WX_PAY_API_KEY);
        requestParameters.put("sign", sign);
        //封装请求参数结束
        String requestXML = WxUtil.getRequestXml(requestParameters);
        log.info("微信支付 xml 参数 ： " + requestXML);

        //调用统一下单接口
        log.info("*******************************   微信支付   ****************************************888");
        log.info("微信支付请求参数\n" + requestParameters);
        String result = wxPostRequest(UNIFIED_ORDER_URL, requestXML);
        //乱码
        try {
            result = new String(result.getBytes("ISO8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        log.info("微信支付响应xml\n" + result);


        //解析xml成map
        Map<String, String> map = WxUtil.doXMLParse(result.toString());
        log.info("微信支付响应map\n" + result);

        return map;
    }



    /**
     * 发送https请求
     *
     * @param requestUrl    请求地址
     * @param outputStr     提交的数据
     * @return 返回微信服务器响应的信息
     */
    public static String wxPostRequest(String requestUrl, String outputStr) {

        String result = null;
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 响应模型
        CloseableHttpResponse response = null;

        try{

            // 创建Post请求
            HttpPost httpPost = new HttpPost(requestUrl);
            StringEntity entity = new StringEntity(outputStr, "UTF-8");
            // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");

            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            result = EntityUtils.toString(responseEntity);


        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }




    /**
     * 签名
     * @param characterEncoding
     * @param parameters
     * @return
     */
    public static String createSignFun(String characterEncoding, SortedMap<Object, Object> parameters,String key) {
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            if (null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + key);
        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
        return sign;
    }










    /*
     * zp
     * 通用微信支付回调接口
     * */
    public static void wxPayNotifyFun(HttpServletRequest request, HttpServletResponse response, PayFunctional  payFunctional ) {
        try {
            //读取参数
            InputStream inputStream;
            StringBuffer sb = new StringBuffer();
            inputStream = request.getInputStream();
            String s;
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((s = in.readLine()) != null) {
                sb.append(s);
            }
            in.close();
            inputStream.close();
            //解析xml成map
            Map<String, String> m = new HashMap<String, String>();
            m = WxUtil.doXMLParse(sb.toString());
            for (Object keyValue : m.keySet()) {
                System.out.println(keyValue + "=" + m.get(keyValue));
            }
            //过滤空 设置 TreeMap
            SortedMap<Object, Object> notifyMap = new TreeMap<Object, Object>();
            Iterator it = m.keySet().iterator();
            while (it.hasNext()) {
                String parameter = (String) it.next();
                String parameterValue = m.get(parameter);

                String v = "";
                if (null != parameterValue) {
                    v = parameterValue.trim();
                }
                notifyMap.put(parameter, v);
            }

            //判断签名是否正确
            String resXml = "";
            if (verifySignFun(characterEncoding,notifyMap, WX_PAY_API_KEY)) {
                if ("SUCCESS".equals((String) notifyMap.get("result_code"))) {
                    // 这里是支付成功

                    String transaction_id = (String) notifyMap.get("transaction_id");//微信、支付宝他们第三方的 订单号
                    String out_trade_no = (String) notifyMap.get("out_trade_no");//我们自己的订单号

                    //支付成功后自己的业务代码
                    boolean success = payFunctional.getResult(transaction_id, out_trade_no);
                    if (success){
                        log.info("************微信支付回调处理成功*******  \n");
                    }else {
                        log.error("***********微信支付回调处理失败*******  \n");
                    }


                    resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                            + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                } else {
                    log.info("支付失败,错误信息：" + notifyMap.get("err_code"));
                    resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                            + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
                }
            } else {
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[通知签名验证失败]]></return_msg>" + "</xml> ";
                log.info("通知签名验证失败");
            }
            //------------------------------
            //处理业务完毕
            //------------------------------
            BufferedOutputStream out = new BufferedOutputStream(
                    response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
            log.info("微信回调接口成功--------");
        } catch (Exception ex) {
            log.error(ex.toString());
            log.error("微信回调接口失败--------");
        }
    }


    /**
     * 验证签名 一般用于回调
     * @param characterEncoding
     * @param packageParams
     * @return
     */
    public static boolean verifySignFun(String characterEncoding, SortedMap<Object, Object> packageParams,String key) {
        StringBuffer sb = new StringBuffer();
        Set es = packageParams.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (!"sign".equals(k) && null != v && !"".equals(v)) {
                sb.append(k + "=" + v + "&");
            }
        }

        sb.append("key=" + key);

        //算出摘要
        String mysign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toLowerCase();
        String tenpaySign = ((String) packageParams.get("sign")).toLowerCase();

        return tenpaySign.equals(mysign);
    }


}
